package org.example.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Aspect
@Component
@Slf4j
public class ForbidRepeatSubmitAop {
    private DefaultRedisScript<Long> defaultRedisScript;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostConstruct
    public void init(){
        defaultRedisScript = new DefaultRedisScript();
        defaultRedisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("forbidRepeatSubmit.lua")));
        defaultRedisScript.setResultType(Long.class);
    }

    @Pointcut("@annotation(org.example.annotation.ForbidRepeatSubmit)")
    private void check(){
    }

    @Around("check()")
    public Object before(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = (Object[])joinPoint.getArgs();
        String token = String.valueOf(args[0]);
        String value = String.valueOf(args[1]);

        List<String> keyList = new ArrayList<>();
        keyList.add(token);

        /*if(token!=null && value!=null){
            //这里如果想执行成功 需要配置RedisConfig key和value的序列化方式都是StringRedisSerializer，判断相等那里才可以
            Long res = stringRedisTemplate.execute(defaultRedisScript, keyList, value);
            log.info("Access token is {} ,value={}", token, value);

            if(res!=null && res==0){
                log.info("验证token失败，token为{}", token);
                //throw new RuntimeException("验证token失败...");
                return "重复提交";
            }else{
                log.info("验证token成功，token为{}", token);
                return joinPoint.proceed();
            }
        }else{
            //throw new RuntimeException("重复提交接口入参错误...");
            return "重复提交";
        }*/
        //如果删除成功 说明是第一次提交的请求
        if(stringRedisTemplate.delete(token)){
            log.info("验证token成功，正常提交，token为{}", token);
            return joinPoint.proceed();
        //删除失败的 说明是重复提交
        }else{
            log.info("重复提交接口入参错误...");
            return "重复提交";
        }
    }
}
